import { message } from "@/utils/message";
import { forceLogout, getOnlineLogsList } from "@/api/system";

export function useRole() {
  const form = reactive({
    userName: ""
  });
  const dataList = ref([]);
  const loading = ref(true);
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 60
    },
    {
      label: "用户名",
      prop: "userName",
      minWidth: 100
    },
    {
      label: "登录 IP",
      prop: "info.ip",
      minWidth: 140
    },
    {
      label: "登录地点",
      prop: "info.address",
      minWidth: 140
    },
    {
      label: "操作系统",
      prop: "info.system",
      minWidth: 100
    },
    {
      label: "浏览器类型",
      prop: "info.browser",
      minWidth: 100
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    }
  ];

  async function handleOffline(row) {
    await forceLogout({ id: row.userId, connectSid: row.connectSid });
    message(`${row.userName}已被强制下线`, { type: "success" });
    onSearch();
  }

  function onSearch() {
    loading.value = true;
    getOnlineLogsList()
      .then(data => {
        dataList.value = data.filter(item =>
          item.userName.includes(form.userName)
        );
        dataList.value = data;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    onSearch,
    resetForm,
    handleOffline
  };
}
